#!C:\Python27\python
import Common as Common
from Common import Logger
from GETHandlerUtil import GetHandler
from PutHandlerUtil import PutHandler
from ADbaseUtil import ADbase

Common.errorLogger = file("errorlog.txt", "a")

import sys, os, msvcrt
msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)

sys.stderr = Common.errorLogger

baseDir = "."
method = os.environ.get("REQUEST_METHOD")
name = baseDir + os.environ.get("PATH_INFO", "")

user = Common.GetUser()
logHelper = Logger(user, "stacklog", Logger.STDMODE, Logger.GET_Request)
Common.putLogger = Common.Logger("putLog", "common", Common.Logger.STDMODE, Common.Logger.PUT_Request)
Common.getLogger = Common.Logger("getLog", user, Logger.STDMODE, Logger.GET_Request)

def HandleAsIs(name, method):
    logHelper.logthis("Begin " + method + " for " + name, logHelper.GET_PUT_Request)
    if method == "GET":
        Common.writeHeaderToOutput(name)
        Common.writeFileToStdout(name)
        adGen = ADbase(logHelper)
        adGen.PopulateAds()
    elif method == "PUT":
        Common.writeStdinToFile(name, "wb")
        Common.writeToOutput(Common.MSG0LEN)
    elif method == "DELETE":
        Common.putLogger.logthis("Control should never reach this Delete for " + name, Common.Logger.PUT_Request)
        Common.DeleteFile(name)
        Common.writeToOutput(Common.MSG0LEN)
    else:
        Common.writeToOutput(Common.MSG501)
    logHelper.logthis("End " + method + " for " + name, logHelper.GET_PUT_Request)


#logHelper.logthis("Begin " + method + " for " + name, logHelper.GET_Request)

def HandleTimeOut(user, name, method):
    if method == "GET":
        Common.timeOut.HandleTimeOut(user)
        
HandleTimeOut(user, name, method)

if method == "MKCOL":
    os.mkdir(os.path.dirname(name))
    Common.writeToOutput(Common.MSG0LEN)
elif method == "DELETE":
    if Common.strContains(name, ".ts"):
        Common.putLogger.logthis("Trying to remove " + name + " at " + str(Common.timepkg.time()), Common.Logger.PUT_Request)
#    Common.DeleteFile(name, True)
    Common.writeToOutput(Common.MSG0LEN)
elif Common.strContains(name, "index.m3u8") or Common.strContains(name, ".key"):   # request for index as-is
    HandleAsIs(name, method)
elif method == "PUT":
#    logHelper.logthis("\nBegin PutHandler: " + name + " for: " + user + " {")
    handler = PutHandler()
    handler.resolve(user, name)
#    logHelper.logthis("PutHandler completed}\n")
    Common.writeToOutput(Common.MSG0LEN)
elif method == "GET":
    logHelper.logthis("\nBegin GetHandler: " + name + " for: " + user + " {")
    handler = GetHandler(user)
    fileReturned = handler.resolve(user, name)
    logHelper.logthis("GetHandler returned: " + str(fileReturned) + " for: " + name + " }\n")
    
#logHelper.logthis("End " + method + " for " + name, logHelper.GET_Request)
logHelper.close()
